package com.yuqingxin.redisCacheApi.common.redisCache;

import com.yuqingxin.redisCacheApi.entity.ApiScheduleEntity;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;

/**
 * @author yuqingxin
 * */
@Log4j2
@Configuration
@EnableScheduling
public class RedisScheduleConfig implements SchedulingConfigurer {

    @Value("${redis-cache.start_time.add_old_api}")
    Boolean isAddOldApi;

    @Value("${redis-cache.start_time.remove_out_api}")
    Boolean isRemoveOutApi;

    @Autowired
    private Executor threadPool;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ApiActiveService apiActiveService;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private Map<String,ScheduledFuture<?>> scheduledFutureMap;

    /**
     * 程序启动时添加定时任务
     * 如果是分布式服务，一般只用一台服务器更新接口缓存就行
     * 可以简单通过设置服务器/容器的环境变量，使用@Value获取变量值来判断该服务器/容器是否是启用更新接口缓存
     * */
    @Override
    public void configureTasks(@Nonnull ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //把之前添加缓存的接口添加到定时任务中
        if (isAddOldApi) {
            //查询所有需要更新缓存的接口的定时任务
            log.info("初始化需缓存接口的定时任务");
            List<ApiScheduleEntity> apiScheduleList = apiActiveService.getApiScheduleList();
            for (ApiScheduleEntity apiSchedule : apiScheduleList) {
                threadPool.execute(()->{
                    try {
                        apiActiveService.initAddApiScheduledTask(apiSchedule);
                    }catch (Exception e){
                        log.error("Init Active Api Error:{}",apiSchedule);
                    }
                });
            }
        }

        //初始化时对长期未使用的接口停止更新缓存
        if (isRemoveOutApi){
            log.info("初始化时对长期未使用的接口停止更新缓存");
            apiActiveService.cancelApiScheduleTaskList();
        }
    }

}
